//app.js
const qiniu = require("/utils/qiniu.min.js");
const mtjwxsdk = require('./utils/mtj-wx-sdk.js');
if (!Array.prototype.findIndex) {
  require('./utils/array-findIndex')
}
// var ald = require('./utils/ald-stat.js');
App({
  onLaunch: function() {
    //调用API从本地缓存中获取数据
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
    if(!wx.getStorageSync('uid')){
      wx.setStorageSync('uid', '')
    }
    this.getSystemInfo();
  },
  // redirectIfNotPermit: function() {
  //   wx.getSetting({
  //     success: (res) => {
  //       wx.navigateTo({
  //         url: "/pages/noauth/noauth"
  //       })
  //     }
  //   })
  // },
  getLocation: function(options) {
    wx.getLocation({
      type: options.type || 'gcj02',
      altitude: true,
      success: function(res) {
        options.success && options.success(res);
      },
      fail: function(res) {
        options.fail && options.fail(res);
      }
    });
  },
  getUserInfo: function(cb, refresh) {
    var that = this;
    if (this.globalData.userInfo && !refresh) {
      typeof cb == "function" && cb(this.globalData.userInfo)
    } else {
      //调用登录接口
      wx.login({
        fail: function(res) {
          // that.redirectIfNotPermit();
        },
        success: function(res) {
          var userCode = res.code,
            uid = wx.getStorageSync('uid');
          if (userCode && (uid == undefined || uid == '')) {
            // that.redirectIfNotPermit();
          } else {
            that.req({
              // url: 'orgmini/user/getBusinessCard',
              url: 'orgmini/user/getNewOtherBusinessCard',
              method: 'POST',
              data:{
                viewUid:uid
              },
              success: function(res) {
                that.globalData.userInfo = res.data;
                if (res.code == 500) {
                  that.showToast({
                    title: res.msg,
                    icon: "none",
                    duration: 3000
                  })
                  wx.removeStorageSync("uid")
                }
                if(res.code == 200){
                  if (res.data.telphone) {
                    typeof cb == "function" && cb(that.globalData.userInfo);
                  }
                }
                

              }
            });
          }
        }
      })
    }
  },
  req: function(cfg) {
    var that = this,
      url = this.globalData.url + cfg.url;
    if (!cfg.noLoading) {
      wx.showLoading({
        title: '加载中',
      })
    }
    var realUrl = cfg.purl ? cfg.purl : url;
    var uid = wx.getStorageSync('uid');
    if (uid || uid == '') {
      if (realUrl.indexOf("?uid=") == -1){
        realUrl += -1 == realUrl.indexOf("?") ? "?" : "&";
        realUrl += "uid=" + uid
      }
    }
    wx.request({
      url: realUrl,
      data: cfg.data,
      method: cfg.method ? cfg.method : 'POST',
      header: {
        'api-client': 'bf7a534e172311ea995200163e05ff66',
        'api-version': '1.3.8',
      },
      success: function(res) {
        // console.log(res,111)
        if (!cfg.noLoading) {
          wx.hideLoading();
        }
        if (res && res.statusCode == 200) {
          if (res.data.code == 401) {
            // that.redirectIfNotPermit();
          } else {
            cfg.success && cfg.success(res.data);
            if (res.data.code == 500) {
              that.showToast({
                title: res.data.msg,
                icon: "none",
                duration: 3000
              })
            }
          }
        } else if (res.statusCode == 404){
            that.showToast({
              title: '系统繁忙，请稍后再试',
              icon: "none",
              duration:3000
            })
        } else {
          that.showToast({
            title: '请求失败',
            icon: "none"
          })
        }
      },
      fail: function(a) {
        if (!cfg.noLoading) {
          wx.hideLoading();
        }
          that.showToast({
            title: '请求失败，请稍后再试',
            icon: "none"
          })
      },
      complete: function(res) {
        var requestData = {
          url: realUrl,
          data: cfg.data,
          response: res
        };
        // console.log(requestData);
        wx.stopPullDownRefresh();
      }
    });
  },
  uploadFile: function(cfg) {
    // console.log(cfg)
    var that = this,
      url = this.globalData.url + cfg.url;
    wx.showLoading({
      title: '上传中',
    })
    wx.uploadFile({
      url: cfg.purl ? cfg.purl : url,
      filePath: cfg.filePath,
      name: 'file',
      header: {
        'token': wx.getStorageSync('token')
      },
      success: function(res) {
        wx.hideLoading();
        if (res && res.statusCode == 200) {
          if (res.data.code == 401) {
            // that.redirectIfNotPermit();
          } else {
            cfg.success(JSON.parse(res.data));
          }
        } else {
          that.showToast({
            title: '上传失败',
          })
        }
      },
      fail: function(a) {
        wx.hideLoading();
        that.showToast({
          title: '上传失败，请稍后再试',
          icon: "none"
        })
      },
      complete: function() {
        wx.stopPullDownRefresh();
      }
    });
  },
  getNameByIdLabel(id, arr) {
    for (let i = 0; i < arr.length; i++) {
      for (let j = 0; j < arr[i].children.length; j++) {
        var arrChild = arr[i].children[j];
        if (arrChild.id == id) {
          return arrChild.text.trim();
        }
      }
    }
    return '';
  },
  uploadToQiNiu: function(config) {
    var that = this;
    // 交给七牛上传
    that.getQiNiuToken(function(data) {
      qiniu.upload(config.filePath,config.success, config.error ? config.error : function(r) {}, {
        uploadURL: 'https://upload.qiniup.com',
        region: 'ECN',
        domain: data.qiniuDomain,
        uptoken: data.upToken,
        shouldUseQiniuFileName:true
      })
    });
  },
  //获取七牛云上传授权
  getQiNiuToken(fun) {
    this.req({
      url: 'wechat/image/uploadApplication',
      data: {},
      method: 'POST',
      success: function(res) {
        if (res.code == 200) {
          typeof fun == "function" && fun(res.data);
        } else {
          wx.showToast({
            title: '获取文件上传权限失败',
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  // 获得设备信息
  getSystemInfo: function () {
    let t = this;
    wx.getSystemInfo({
      success: function (res) {
        t.globalData.systemInfo = res
      },
      fail: function (err) {
        console.log(err)
      }
    });
  },
  onShow: function(e) {
    let that = this;
    wx.getSystemInfo({
      success: res => {
        let modelmes = res.model;
        if (modelmes.search('iPhone X') != -1) {
          that.globalData.isIphoneX = true
        } else {
          that.globalData.isIphoneX = false
        }
      }
    })
  },
  showToast: function(cfg) {
    wx.showToast(cfg);
  },
  globalData: {
    userInfo: null,
    systemInfo: null, //客户端设备信息
    refresh:"1",//是否刷新
    // 测试
    activityMiniAppId: 'wx41c81e0c8b670ad8',
    activityMiniEnvVersion: 'trial',
    blessingMiniAppId: 'wx5388911760d25547',
    blessingMiniEnvVersion: 'trial',
    url: 'https://test.yiqilaiwang.com/',
    // 正式
    // activityMiniAppId: 'wx15f071f49d1edf94',
    // activityMiniEnvVersion: 'release',
    // blessingMiniAppId: 'wx389cd2531675cd84',
    // blessingMiniEnvVersion: 'release',
    // url: 'https://www.yiqilaiwang.com/',
    // // url: 'https://demo.yiqilaiwang.com/',
  },
  getRefresh: function (cb, refresh) {
    var that = this;
    if (!refresh) {
      typeof cb == "function" && cb(this.globalData.refresh)
    } else {
      this.globalData.refresh = refresh;
    }
  },
});

/**
 * 定义克隆方法
 */
Object.defineProperty(
  Object.prototype,
  'clone', {
    value: function() {
      var cloneSelf = {};
      for (var key in this) {
        cloneSelf[key] = this[key];
      }
      return cloneSelf;
    },
    writable: false,
    enumerable: false,
    configurable: false
  });